"""
Agent Boss 简化测试文件
用于快速验证基本功能
"""

import os
import sys
import django
from django.conf import settings

# 添加项目路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置Django设置
if not settings.configured:
    settings.configure(
        DEBUG=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'rest_framework',
            'agent_boss',
        ],
        ROOT_URLCONF='agent_boss.urls',
        SECRET_KEY='test-secret-key',
        USE_TZ=True,
    )

django.setup()

from django.test import TestCase, Client
from django.contrib.auth.models import User
import json
from unittest.mock import patch, MagicMock


class SimpleAgentBossTest(TestCase):
    """简化测试Agent Boss功能"""
    
    def setUp(self):
        """测试前准备"""
        self.client = Client()
        self.url = '/agent_boss/chat/'
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )
    
    @patch('agent_boss.views.JwtUtils.get_user_id_from_token')
    @patch('agent_boss.views.BossAgent')
    def test_basic_chat_functionality(self, mock_boss_agent_class, mock_jwt_utils):
        """测试基本聊天功能"""
        print("测试基本聊天功能...")
        
        # Mock JWT工具
        mock_jwt_utils.return_value = self.user.id
        
        # Mock BossAgent
        mock_agent_instance = MagicMock()
        mock_agent_instance.run.return_value = {"response": "测试回复成功！"}
        mock_boss_agent_class.return_value = mock_agent_instance
        
        # 准备请求数据
        data = {
            'question': '你好，请帮我生成一份简历',
            'session_id': 'test_session_001'
        }
        
        # 发送请求
        response = self.client.post(
            self.url,
            data=json.dumps(data),
            content_type='application/json',
            HTTP_AUTHORIZATION='Bearer test_token'
        )
        
        # 验证响应
        self.assertEqual(response.status_code, 200)
        response_data = response.json()
        self.assertEqual(response_data['code'], 200)
        self.assertEqual(response_data['message'], 'ok')
        self.assertIn('data', response_data)
        self.assertEqual(response_data['data']['response'], '测试回复成功！')
        
        print("基本聊天功能测试通过")
    
    def test_authentication_failure(self):
        """测试认证失败"""
        print("测试认证失败...")
        
        data = {
            'question': '测试问题',
            'session_id': 'test_session_001'
        }
        
        # 不提供认证头
        response = self.client.post(
            self.url,
            data=json.dumps(data),
            content_type='application/json'
        )
        
        # 验证响应
        self.assertEqual(response.status_code, 200)
        response_data = response.json()
        self.assertEqual(response_data['code'], 0)
        self.assertIn('认证失败', response_data['message'])
        
        print("认证失败测试通过")
    
    def test_empty_question(self):
        """测试空问题"""
        print("测试空问题...")
        
        data = {
            'question': '',
            'session_id': 'test_session_001'
        }
        
        response = self.client.post(
            self.url,
            data=json.dumps(data),
            content_type='application/json',
            HTTP_AUTHORIZATION='Bearer test_token'
        )
        
        # 验证响应
        self.assertEqual(response.status_code, 200)
        response_data = response.json()
        self.assertEqual(response_data['code'], 0)
        self.assertEqual(response_data['message'], '问题不能为空')
        
        print("空问题测试通过")
    
    def test_text_cleaning(self):
        """测试文本清理功能"""
        print("测试文本清理功能...")
        
        from agent_boss.views import clean_text
        
        # 测试emoji清理
        text_with_emoji = "Hello World"
        cleaned = clean_text(text_with_emoji)
        self.assertEqual(cleaned, "Hello World")
        
        # 测试HTML清理
        text_with_html = "<p>Hello</p><br/>World"
        cleaned = clean_text(text_with_html)
        self.assertEqual(cleaned, "pHellopbrWorld")
        
        # 测试中文保留
        chinese_text = "你好世界！"
        cleaned = clean_text(chinese_text)
        self.assertEqual(cleaned, chinese_text)
        
        print("文本清理功能测试通过")
    
    def run_all_tests(self):
        """运行所有测试"""
        print("开始运行Agent Boss简化测试...")
        print("=" * 50)
        
        try:
            self.test_basic_chat_functionality()
            self.test_authentication_failure()
            self.test_empty_question()
            self.test_text_cleaning()
            
            print("=" * 50)
            print("所有测试通过！Agent Boss功能正常")
            return True
            
        except Exception as e:
            print("=" * 50)
            print(f"测试失败: {str(e)}")
            return False


def run_simple_test():
    """运行简化测试"""
    print("初始化测试环境...")
    
    # 创建测试实例
    test_instance = SimpleAgentBossTest()
    test_instance.setUp()
    
    # 运行测试
    success = test_instance.run_all_tests()
    
    if success:
        print("\n测试总结:")
        print("基本聊天功能: 通过")
        print("认证验证: 通过")
        print("参数验证: 通过")
        print("文本清理: 通过")
        print("\nAgent Boss API 功能正常，可以投入使用！")
    else:
        print("\n测试失败，请检查代码")
    
    return success


if __name__ == '__main__':
    run_simple_test()
